setScreenMetrics(device.width, device.height);

app_func = {
    appName: "今日头条极速版",
    packageName: "com.ss.android.article.lite",
    mainActivity: "com.ss.android.article.lite.activity.SplashActivity",
    bounds: {
        task_button: null,
        mine_button: null,
    }
}

let current_package = app_func.packageName;
function launchAppEnhance(app_name) {
    let result;
    let thread = threads.start(function () {
        toastLog("检查是否有打开权限!");
        while (true) {
            var allow = text("允许").findOne(5000);
            if (allow) {
                sleep(1000)
                toastLog("发现允许授权!");
                allow.click();
                sleep(1000);
                thread.interrupt();
                break;
            }
        }
    });
    sleep(1000);
    if (currentPackage() != current_package) {
        result = launchApp(app_name);
        sleep(3000);
    }
    else {
        result = currentPackage();
    }
    thread.interrupt();
    return result;
}

function find_button_by_text(textstr) {
    toastLog("寻找按钮:" + textstr);
    var task_button = null
    for (var i = 0; i < 2; i++) {
        task_button = text(textstr).findOne(3000);
        if (task_button) {
            console.log("找到控件text:", task_button.text());
            break;
        }
        else {
            console.log("第" + (i + 1) + "次未找到");
            sleep(1000)
            continue;
        }
    }

    return task_button
}

function find_button_by_textStartsWith(textstr) {
    toastLog("寻找按钮:" + textstr);
    var task_button = null
    for (var i = 0; i < 2; i++) {
        sleep(3000)
        task_button = textStartsWith(textstr).findOne(3000);
        if (task_button) {
            console.log("找到控件text:", task_button.text());
            break;
        }
        else {
            console.log("第" + (i + 1) + "次未找到");
            sleep(1000)
            continue;
        }
    }
    sleep(1000)
    return task_button
}

//关闭各种弹窗广告
function close_all_ad() {
    try { textStartsWith('今日任务完成了').findOne(500).click(); } catch (e) { }
    try { text('我知道了').findOne(500).click(); } catch (e) { }
    try { text('跳过').findOne(500).click(); } catch (e) { }
    try { text('禁止').findOne(500).click(); } catch (e) { }
    try { text('以后再说').findOne(500).click(); } catch (e) { }
    //打开签到提醒
    try {
        打开签到 = textStartsWith('签到成功').findOne(500)
        按钮 = 打开签到.parent().child(4)
        if (按钮) {
            click_button(按钮.bounds())
            toastLog("1")
        }
    } catch (error) { }

}

function find_watch_video_button() {
    toastLog("开始寻找看视频奖励按钮------------------:");
    sleep(3000)
    var target_button = textStartsWith("看视频再领").findOne(4000);
    if (target_button) {
        console.log("控件text:", target_button.text());
        app_func.bounds.watch_video_button = target_button.bounds()
        return 0;
    }
    else {
        toastLog("没找到看视频奖励按钮");
        return -1;
    }
}

function find_close_adv_button() {
    toastLog("开始寻找关闭广告按钮------------------:");
    var target_button = text("关闭广告").findOne(2 * 1000);
    if (target_button) {
        //等3秒再找找
        sleep(3000)
        target_button = text("关闭广告").findOne(2 * 1000);
        if (target_button) {
            toastLog("控件text:", target_button.text());
            click_button(target_button.bounds())
            return 0;
        }
        return -1
    }
    else {
        toastLog("没找到关闭广告按钮");
        return -1;
    }
}

function find_goto_book_button() {
    console.log("开始寻找加入书架按钮------------------:");
    var target_button = text("加入书架").findOne(4000);
    if (target_button) {
        console.log("成功找到目标按钮:", target_button.bounds());
        console.log("控件className:", target_button.className());
        console.log("控件text:", target_button.text());
        app_func.bounds.goto_book_button = target_button.bounds()
        return 0;
    }
    else {
        console.log("没找到关闭广告按钮");
        return -1;
    }
}

//传入坐标参数
function click_button(bounds) {
    toastLog("点击按钮:" + bounds.centerX() + bounds.centerY());
    sleep(1000);
    click(bounds.centerX(), bounds.centerY());
    sleep(2000)
}

function open_baoxiang() {
    toastLog("开始点击开宝箱");
    var baoxiang = find_button_by_textStartsWith("treasure-box")
    if (baoxiang) {
        click_button(baoxiang.bounds());
    }
    else {
        toastLog("没有发现开宝箱得金币");
        return -1
    }
    return 0
}

function handle_search_tv_task() {
    toastLog("开始搜索电视剧任务");
    //进入任务界面
    click_button(app_func.bounds.task_button)

    var 去搜索 = auto_find_button("去搜索")
    if (去搜索) {
        click_button(去搜索.bounds())
        setText("最新电视剧")
        var 搜索 = find_button_by_text("搜索")
        if (搜索) {
            click_button(搜索.bounds())
        }
        else {
            toastLog("没找到搜索按钮")
            clean_obs()
        }
    }
    else {
        toastLog("没找到去搜索按钮")
        clean_obs()
    }
    //返回
    err_back()

    return 0;
}

function handle_watch_vid_single_task() {
    toastLog("看视频再奖励任务");
    sleep(3000)
    //签到成功触发看视频再奖励按钮
    var strlist = ["看视频再领", "看完视频再"]
    var 看视频再奖励 = null
    for (var i = 0; i < strlist.length; i++) {
        看视频再奖励 = find_button_by_textStartsWith(strlist[i])
        if (看视频再奖励) {
            break;
        }
    }
    if (看视频再奖励) {
        click_button(看视频再奖励.parent().bounds())
        if (handle_after_open_vid() >= 0) {
            toastLog("签到视频奖励完成")
        }
        else {
            toastLog("签到视频奖励失败")
            return -1
        }
    }
    else {
        //看视频再奖励流程失败
        toastLog("看视频再奖励流程失败");
        return -1
    }
    return 0
}

//从书架删除书
function handle_del_book() {
    toastLog("开始删除书架");
    //进入书架 点击编辑 选中所有书 点击删除
    find_book_button()
    click_button(app_func.bounds.book_button)
    var edit_button = text("编辑").findOne(4000);
    if (edit_button) {
        edit_button.click();
        var checkboxlist = className("android.widget.CheckBox").find(5000);
        if (checkboxlist.length > 0) {
            console.log("找到" + checkboxlist.length + "本书");
            for (var i = 0; i < checkboxlist.length; i++) {
                sleep(2000);
                checkboxlist[i].click();
                sleep(2000);
            }
            //点击删除
            var del_button = textStartsWith("删除").findOne(2000);
            sleep(2000)
            if (del_button) {
                click_button(del_button.bounds())
                sleep(2000)
                var queren = text("确认").findOne(2000);
                if (queren) {
                    queren.click()
                    console.log("删除成功")
                }
                else {
                    console.log("未找到确认按钮")
                }
            }
            else {
                console.log("未找到删除按钮")
            }
        }
        else {
            console.log("没有书可删除")
        }
    }
    else {
        console.log("没有编辑按钮")
    }
    return
}

//看书
function handle_watch_book(dotimes) {
    var ifbook = 0
    //先接任务找到福利按钮
    find_task_button()
    click_button(app_func.bounds.task_button)

    for (var i = 0; i < 5; i++) {
        var targetButton = text("阅读10分钟").findOne(4000);
        if (targetButton) {
            parent = targetButton.parent().parent();
            var tb = parent.child(1).child(0);
            toastLog("阅读10分钟任务:" + tb.text());
            if (tb.text() == "已完成") {
                return 0
            }
            else {
                ifbook = 1
                break;
            }
        }
        else {
            //关广告，回任务界面
            close_all_ad();
            find_task_button()
            click_button(app_func.bounds.task_button)
        }
    }
    if (ifbook == 0) {
        toastLog("没有发现阅读任务");
        return -1
    }

    toastLog("开始看书");
    //进入书架 点击编辑 选中所有书 点击删除
    find_book_button()
    click_button(app_func.bounds.book_button)

    var book = textContains("章").findOne(5000);
    if (book) {
        sleep(2000);
        console.log(book.text());
        click_button(book.bounds())
        sleep(2000);
        var random_min = 11 * 60
        var random_max = 13 * 60
        var watchtime = random(random_min, random_max)
        for (var i = 0; i < watchtime; i++) {
            sleep(1000)
            if ((i + 1) % 60 == 0) {
                toastLog("已经阅读" + parseInt((i + 1) / 60) + "分钟");
            }
            //挂机无法增长时间
            if ((i + 1) % 10 == 0) {
                _left_move();
            }
        }
        toastLog("看书任务完成");
    }
    else {
        console.log("没有书可读")
    }

    return
}

function handle_watch_video_task() {
    toastLog("开始做看视频或文章任务");
    //先接任务找到任务按钮

    //任务按钮变倒计时 app_func.bounds.task_button
    click_button(app_func.bounds.task_button)

    //进入任务页面寻找入口
    //检查还可以完成几次
    var targetButton = null;
    var dotimes = 0;
    for (var i = 0; i < 3; i++) {
        targetButton = textContains('篇').findOne(5000)
        if (targetButton) {
            // var dotimes = 10 - parseFloat(targetButton.text().slice(0, 2))
            // if (dotimes == 0) {
            //     toastLog("看文章或视频任务已完成");
            //     return 0
            // }
            // break
            dotimes = 10
        }
        else {
            //关广告，回任务界面
            close_all_ad();
            click_button(app_func.bounds.task_button)
        }
    }

    toastLog("剩余" + dotimes + "次看视频文章任务");

    handle_watch_article(dotimes)

    err_back()
    return 0
}

function handle_watch_article(times) {
    if (times == 0) {
        return
    }
    toastLog('开始阅读文章');
    click_button(app_func.bounds.task_button)
    var quyuedu = text('阅读文章或视频').findOne(5000)
    if (quyuedu) {
        var 去阅读 = quyuedu.parent().find(className('android.view.View').clickable(true))
        if (去阅读) {
            去阅读.click()
            var targettimes = times
            var watchtimes = 0
            while (watchtimes < targettimes) {
                //刷新文章
                sleep(3000)
                _down_move(800)
                var articlelist = id('com.ss.android.article.lite:id/a08').find()
                if (articlelist.length > 0) {
                    toastLog("找到" + articlelist.length + "篇文章")
                    sleep(2000)
                    //开始看文章 
                    click_button(articlelist[2].bounds())
                    sleep(2000)
                    //关闭授权
                    try {
                        text("不允许").findOne(2000).click()
                        toastLog("不允许")
                    } catch (error) {
                    }
                    if (!textStartsWith('写评论').exists()) {
                        toastLog('没评论,不是文章');
                        back();
                        sleep(1000);
                        continue;
                    }
                    sleep(2000);
                    for (var j = 0; j < 30; j++) {
                        sleep(1000)
                        _up_move()
                        分享朋友圈 = text("分享朋友圈").boundsInside(0, 0, device.width, device.height * 0.8).findOne(500)
                        分享微信 = text("分享微信").boundsInside(0, 0, device.width, device.height * 0.8).findOne(500)
                        if (分享朋友圈 && 分享微信) {
                            console.log("位置已找到")
                            sleep(5 * 1000)
                            break
                        }
                    }
                    toastLog("阅读完成,返回")
                    watchtimes++
                    back();
                    if (watchtimes >= targettimes) {
                        toastLog("阅读任务完成")
                        break;
                    }
                }
            }
            toastLog("阅读任务完成")
        }
    }
    else {
        toastLog("没找到去阅读按钮")
        return -1
    }
    return 0
}
function handle_after_open_vid() {
    for (var i = 0; i < 60; i++) {
        sleep(1000)
        //每5秒检查一次关闭按钮是否出现
        if ((i + 1) % 5 == 0) {
            console.log("检查是否出现退出按钮");
            if (id("tt_video_ad_close").exists()) {
                id("tt_video_ad_close").click()
                return 0
            }
            if (find_close_adv_button() >= 0) {
                return 0
            }
        }
    }
    return -1;
}

//向下滑
function _down_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向下滑动")
    let x = device.width / 2
        , t = device.height * 4 / 5
        , b = device.height * 1 / 5
    sml_move(x, b, x, t, truespeed + random(50, 100));
    sleep(1000);
}
//向上滑
function _up_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向上滑动")
    let x = device.width / 2
        , t = device.height * 1 / 5
        , b = device.height * 4 / 5
    sml_move(x, b, x, t, truespeed + random(50, 100));
    sleep(1000);
}

//向左滑
function _left_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向左滑动")
    let y = device.height / 2
        , t = device.width * 1 / 5
        , b = device.width * 4 / 5
    sml_move(b, y, t, y, truespeed + random(50, 100));
    sleep(1000);
}

//向右滑
function _rigth_move(speed) {
    var truespeed = 200
    if (speed) {
        truespeed = speed
    }
    console.log("向右滑动")
    let y = device.height / 2
        , t = device.width * 4 / 5
        , b = device.width * 1 / 5
    sml_move(b, y, t, y, truespeed + random(50, 100));
    sleep(1000);
}

function sml_move(qx, qy, zx, zy, time) {
    //仿真随机带曲线滑动: qx, qy, zx, zy, time 代表起点x,起点y,终点x,终点y,过程耗时单位毫秒
    var xxy = [time];
    var point = [
        { "x": qx, "y": qy },
        { "x": random(qx - 100, qx + 100), "y": random(qy, qy + 50) },
        { "x": random(zx - 100, zx + 100), "y": random(zy, zy + 50) },
        { "x": zx, "y": zy }
    ];
    for (let i = 0; i < 1; i += 0.08) {
        xxyy = [parseInt(bezier_curves(point, i).x), parseInt(bezier_curves(point, i).y)]
        xxy.push(xxyy);
    }
    gesture.apply(null, xxy);
}

function bezier_curves(cp, t) {
    cx = 3.0 * (cp[1].x - cp[0].x);
    bx = 3.0 * (cp[2].x - cp[1].x) - cx;
    ax = cp[3].x - cp[0].x - cx - bx;
    cy = 3.0 * (cp[1].y - cp[0].y);
    by = 3.0 * (cp[2].y - cp[1].y) - cy;
    ay = cp[3].y - cp[0].y - cy - by;

    tSquared = t * t;
    tCubed = tSquared * t;
    result = { "x": 0, "y": 0 };
    result.x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
    result.y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
    return result;
};

//自动调整按钮位置并点击  适用于在屏幕外无法点击的按钮
function auto_find_button(textstr) {
    var targetbutton = find_button_by_textStartsWith(textstr)
    var trytimes = 3
    if (targetbutton) {
        toastLog("device.width:" + device.width + "device.height:" + device.height)
        toastLog("x:" + targetbutton.bounds().centerX() + "y:" + targetbutton.bounds().centerY())
        //至少把空间拖到 屏幕 device.height * 1/5   至  device.height * 4/5 之间
        while (targetbutton.bounds().centerY() > device.height * 4 / 5) {
            var uptimes = Math.ceil((targetbutton.bounds().centerY() - device.height * 4 / 5) / (device.height * 4 / 5 - device.height * 1 / 5))
            toastLog("需要滑动调整位置次数:" + uptimes)
            for (var i = 0; i < uptimes; i++) {
                _up_move()
                sleep(2000)
            }
            targetbutton = find_button_by_textStartsWith(textstr)
            trytimes--
            if (trytimes <= 0) {
                break
            }
        }

        while (targetbutton.bounds().centerY() < device.height * 1 / 5) {
            var uptimes = Math.ceil((device.height * 1 / 5 - targetbutton.bounds().centerY()) / (device.height * 4 / 5 - device.height * 1 / 5))
            toastLog("需要滑动调整位置次数:" + uptimes)
            for (var i = 0; i < uptimes; i++) {
                _down_move()
                sleep(2000)
            }
            targetbutton = find_button_by_textStartsWith(textstr)
            trytimes--
            if (trytimes <= 0) {
                break
            }
        }

        targetbutton = find_button_by_textStartsWith(textstr)
        if (targetbutton) {
            toastLog("找到按钮:" + textstr)
        }
        else {
            toastLog("没找到按钮:" + textstr)
        }
    }
    return targetbutton
}

function clean_obs() {
    var result = null

    if (is_mainAct()) {
        //关闭各种广告
        close_all_ad()
        result = 0
    }
    else {
        //存在是在主页 也有弹窗
        result = err_back()
    }
    return result
}

function is_mainAct() {
    sleep(1000)
    var curact = currentActivity();
    if (curact != app_func.mainActivity) {
        toastLog("不在主界面")
        return false
    }
    else {
        toastLog("当前是主界面")
        return true
    }
}

function err_back() {
    var curact = null;
    for (var i = 0; i < 3; i++) {
        curact = currentActivity()
        sleep(1000)
        if (curact != app_func.mainActivity) {
            toastLog("尝试回到主界面")
            back();
            sleep(3000)
        }
        else {
            toastLog("已回到当前主界面")
            break
        }
    }

    if (curact != app_func.mainActivity) {
        toastLog("回主界面失败")
        return -1
    }

    return 0
}

function timehandle() {

    if (!is_mainAct()) {
        err_back()
    }
    click_button(app_func.bounds.task_button)

    var date = new Date();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();

    if (h >= 20 || h < 2) {
        //进入睡觉任务
        var 睡觉赚钱 = find_button_by_textStartsWith("睡觉赚钱")
        if (睡觉赚钱) {
            click_button(睡觉赚钱.bounds())
        }
        else {
            toastLog("睡觉赚钱按钮没找到")
        }

        var 我要睡了 = find_button_by_textStartsWith("我要睡了")
        if (我要睡了) {
            click_button(我要睡了.bounds())
        }
        else {
            toastLog("已领任务或者没找到")
        }
    }
    if (h < 20 && h >= 9) {
        //完成睡觉任务
        //进入睡觉任务
        var 睡觉赚钱 = find_button_by_textStartsWith("睡觉赚钱")
        if (睡觉赚钱) {
            click_button(睡觉赚钱.bounds())
        }
        else {
            toastLog("睡觉赚钱按钮没找到")
        }
        var 我睡醒了 = find_button_by_textStartsWith("我睡醒了")
        if (我睡醒了) {
            click_button(我睡醒了.bounds())
            let 领取金币 = textMatches("领取\\d+金币").findOne(5000);
            if (领取金币) {
                click_button(领取金币.bounds())
                toastLog(领取金币.text())
                //顺手再试一下能不能接我要睡了的任务
                var 我要睡了 = find_button_by_textStartsWith("我要睡了")
                if (我要睡了) {
                    click_button(我要睡了.bounds())
                }
                else {
                    toastLog("已领任务或者没找到")
                }
            }
        }
        else if (领取金币2 = textMatches("领取\\d+金币").findOne(5000)) {
            click_button(领取金币2.bounds())
            toastLog(领取金币2.text())
            //顺手再试一下能不能接我要睡了的任务
            var 我要睡了 = find_button_by_textStartsWith("我要睡了")
            if (我要睡了) {
                click_button(我要睡了.bounds())
            }
            else {
                toastLog("已领任务或者没找到")
            }
        }
        else {
            toastLog("已点我睡醒任务或者没找到")
        }
    }

    err_back();

    return 0
}

function find_task_button() {
    toastLog("查找任务按钮坐标");
    var target_button = textStartsWith("首页").findOne(4000);
    if (target_button) {
        toastLog("控件text:", target_button.text());
        var task_button = target_button.parent().parent().child(3)
        app_func.bounds.task_button = task_button.bounds()

        var mine_button = target_button.parent().parent().child(4)
        app_func.bounds.mine_button = mine_button.bounds()
        toastLog("任务按钮坐标:" + task_button.bounds())
        return 0;
    }
    else {
        toastLog("没找到看视频奖励按钮");
        return -1;
    }
}

app_func.main = function () {
    console.log("start...");
    var open_app = launchAppEnhance(app_func.appName);
    if (open_app) {
        sleep(5 * 1000)
        close_all_ad()  //加载慢了会判断不在主界面
        //寻找任务按钮触发签到
        //       var 任务控件 = find_button_by_text("任务")
        if (find_task_button() >= 0) {
            //记录按钮坐标，开宝箱后 任务变成倒计时 
            click_button(app_func.bounds.task_button)
        }
        else {
            toastLog("没找到任务界面")
            clean_obs()
        }

        //签到成功触发看视频再奖励按钮
        if (handle_watch_vid_single_task() < 0) {
            clean_obs()
        }

        //顺手开宝箱
        if (open_baoxiang() >= 0) {
            if (handle_watch_vid_single_task() < 0) {
                clean_obs()
            }
        }

        //做阅读任务
        if (handle_watch_video_task() < 0) {
            clean_obs()
        }

        //搜索电视剧任务
        if (handle_search_tv_task() < 0) {
            clean_obs()
        }
        //走路赚钱
        if (!is_mainAct()) {
            err_back()
        }
        click_button(app_func.bounds.task_button)

        var 走路赚钱 = auto_find_button("走路赚钱")
        if (走路赚钱) {
            click_button(走路赚钱.bounds())
            //授权计步
            var 好的 = text("好的").findOne(2000)
            if (好的) {
                click_button(好的.bounds())
            }
            var 领取 = find_button_by_textStartsWith("领取")
            if (领取) {
                click_button(领取.bounds())
            }
        }
        else {
            toastLog("没找到走路赚钱")

        }
        clean_obs()

        //吃饭补贴
        if (!is_mainAct()) {
            err_back()
        }
        click_button(app_func.bounds.task_button)

        var 吃饭补贴 = find_button_by_text("吃饭补贴")
        if (吃饭补贴) {
            click_button(吃饭补贴.bounds())
            var 领取 = find_button_by_textStartsWith("领取")
            if (领取) {
                click_button(领取.bounds())
                toastLog("领取")
                if (handle_watch_vid_single_task() < 0) {
                    toastLog("看视频再奖失败")
                }
            }
            else {
                toastLog("已领过或无法领取")
            }
        }
        else {
            toastLog("没找到吃饭补贴")
        }
        clean_obs()

        //睡觉赚钱
        timehandle()
    }
    else {
        console.log("app启动失败");
    }
    console.log("end...");
}

//提现处理
function handle_withdraw() {
    toastLog("开始提现任务")
    for (var i = 0; i < 3; i++) {
        if (app_func.bounds.mine_button) {
            click_button(app_func.bounds.mine_button)
            let 去提现 = text("提现兑换").findOne(2000)
            if (去提现) {
                click_button(去提现.bounds())
                var 立即提现 = text("立即提现").findOne(2000)
                if (立即提现) {
                    click_button(立即提现.bounds())
                    close_all_ad()
                    back() //返回
                    return 0
                }
            }
            else {
                toastLog("没有找到去提现")
                //有先弹倒计时广告的情况
                close_time_adv()
                close_all_ad()  //直接领取到达 成就界面
            }
        }
        else {
            toastLog("没有找到'我的'界面")
            clean_obs()
        }
    }
    back() //返回
    return -1
}

try {
    app_func.main();
} catch (error) {
    console.log(error)
}

events.on("exit", function () {
    var storage = storages.create("xiangxiangyuedu");
    storage.put("script_running_status", "end");
});